//
//  LYAddressBookView.m
//  SZBank
//
//  Created by LuoYao on 16/7/12.
//  Copyright © 2016年 LuoYao. All rights reserved.
//

#import "LYAddressBookView.h"

@interface LYAddressBookView ()<UITableViewDataSource,UITableViewDelegate,CNContactViewControllerDelegate>
{
    NSMutableArray *_personList;/**< 联系人列表 */
    NSMutableArray *_contactList;/**< contact列表 */
    NSInteger _selectIndex;/**< 选中的行 */
    UILabel *_personName;
    UIImageView *_headerImageView;
}
@property (nonatomic) CNContactViewController *contactViewController; /**< 系统添加联系人控制器 */
@property (nonatomic) UINavigationController *navigationController;/**< 导航控制器 */
@property (nonatomic) CNContactStore *contactStore;/**< 操作事件 */
@property (nonatomic) UITableView *list;/**< 通讯录显示列表 */

@end
@implementation LYAddressBookView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        
         [self initDataSource];
        
        //背景
        self.backImageView.image = [LocalDataManager getImageWithSourceOfPath:@"通讯录"];
        
        
        //提示文字
        UILabel *allPerson = [[UILabel alloc] initWithFrame:CGRectMake(_cKwidth * 0.01, 0, _cKwidth * 0.35, 50)];
        allPerson.text = @"全部联系人";
        allPerson.font = [UIFont systemFontOfSize:FONT_SIZE];
        allPerson.textAlignment = NSTextAlignmentCenter;
        
        [self addSubview:allPerson];
        
        //输入框
        UITextField *searchField = [[UITextField alloc] initWithFrame:CGRectMake(_cKwidth * 0.01, _cKheight * 0.07, _cKwidth * 0.35, 50)];
        [searchField setBackground:[LocalDataManager getImageWithSourceOfPath:@"备忘录_搜索"]];
        
        [self addSubview:searchField];
        
        
        //显示列表
        [self addSubview:self.list];
        
        

        //右侧Btn
        NSArray *btnTitle = @[@"备忘录_增加",@"备忘录_删除"];
        for (int i = 0; i < 2; i ++) {
            UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(_cKwidth * 0.7 + i * _cKwidth * 0.15 , _cKheight * 0.23, _cKwidth * 0.12, 40)];
            btn.tag = 1000 + i;
            [btn setBackgroundImage:[LocalDataManager getImageWithSourceOfPath:btnTitle[i]] forState:UIControlStateNormal];
            [btn addTarget:self action:@selector(action_btnClick:) forControlEvents:UIControlEventTouchUpInside];
            [self addSubview:btn];
        }
        

        //右侧View
        _headerImageView = [[UIImageView alloc] initWithFrame:CGRectMake(_cKwidth * 0.4, _cKheight * 0.05, _cKwidth * 0.1, _cKwidth * 0.1)];
        [self addSubview:_headerImageView];
        
        _personName = [[UILabel alloc] initWithFrame:CGRectMake(_cKwidth * 0.4, _cKheight * 0.23, _cKwidth * 0.2, _cKheight * 0.08)];
        _personName.font = [UIFont systemFontOfSize:FONT_SIZE + 2];
        
        [self addSubview:_personName];
        
        
        
        NSArray *titles = @[@"电话",@"地址"];
        NSArray *opptions = @[@"工作",@"住宅"];
        
        for (int i = 0; i < titles.count; i ++) {
            UILabel *lb = [[UILabel alloc] initWithFrame:CGRectMake(_cKwidth * 0.4, _cKheight * 0.3 + i * _cKheight * 0.3, _cKwidth * 0.59, _cKheight * 0.08)];
            lb.text = titles[i];
            lb.font = [UIFont systemFontOfSize:FONT_SIZE];
            [self addSubview:lb];
            
            for (int j = 0; j < opptions.count; j ++) {
                UILabel *lb = [[UILabel alloc] initWithFrame:CGRectMake(_cKwidth * 0.4 , _cKheight * 0.38 + j * _cKheight * 0.08 + i * _cKheight * 0.3, _cKwidth * 0.2, _cKheight * 0.08)];
                lb.text = opptions[j];
                lb.font = [UIFont systemFontOfSize:FONT_SIZE];
                [self addSubview:lb];
                
                
                    
                UILabel *text = [[UILabel alloc] initWithFrame:CGRectMake(_cKwidth * 0.6 , _cKheight * 0.38 + j * _cKheight * 0.08 + i * _cKheight * 0.3, _cKwidth * 0.2, _cKheight * 0.08)];
                text.font = [UIFont systemFontOfSize:FONT_SIZE];
                text.tag = 1000 + i * 2 + j;
                [self addSubview:text];
                
            }
            
        }
        
    }
    return self;
}




/**< 初始化数据源 */
- (void)initDataSource{
    
    _personList = [NSMutableArray array];
    _contactList = [NSMutableArray array];
    
    //获取联系人列表
    //获取哪些值
    CNContactFetchRequest *request=[[CNContactFetchRequest alloc]initWithKeysToFetch:@[CNContactGivenNameKey,CNContactFamilyNameKey,CNContactPhoneNumbersKey,CNContactPostalAddressesKey,CNContactImageDataKey]];
    
    [self.contactStore enumerateContactsWithFetchRequest:request error:nil usingBlock:^(CNContact * _Nonnull contact, BOOL * _Nonnull stop) {
        
        
        //列表赋值
        [_contactList addObject:[contact mutableCopy]];
        
        NSString *personName = [NSString stringWithFormat:@"%@ %@",contact.givenName,contact.familyName];
        NSString *phoneNunber = contact.phoneNumbers.firstObject.value.stringValue;
        NSString *workAddress = contact.postalAddresses.firstObject.value.street;
        NSData *imageData = contact.imageData;
        
        
        if (!workAddress) {
            workAddress = @"";
        }
        
        if (!imageData) {
            imageData = [NSData data];
        }
        
        if (!phoneNunber) {
            phoneNunber = @"";
        }
        
        NSDictionary *dic = @{@"imageData":imageData,@"personName":personName,@"phoneNumber":phoneNunber,@"workAddress":workAddress};
        //显示数据赋值
        [_personList addObject:dic];
        
    }];
    
    
    [self.list reloadData];

    
}


//根据名称查询联系人
- (NSArray *)queryContactWithName:(NSString *)name{
    // 检索条件
    NSPredicate *predicate = [CNContact predicateForContactsMatchingName:name];
    // 提取数据 （keysToFetch:@[CNContactGivenNameKey]是设置提取联系人的哪些数据）
    NSArray *contact = [self.contactStore unifiedContactsMatchingPredicate:predicate keysToFetch:@[CNContactGivenNameKey] error:nil];
    return contact;
}

//删除联系人
- (void)deleteContact:(CNMutableContact *)contact{
    // 创建联系人请求
    CNSaveRequest *deletedRequest = [[CNSaveRequest alloc] init];
    [deletedRequest deleteContact:contact];

    //写入请求
    NSError *error = nil;
    [self.contactStore executeSaveRequest:deletedRequest error:&error];
    
    //重新请求和刷新
    [self initDataSource];
    
    NSLog(@"______________");
}


//控件赋值

#pragma mark - 点击事件
- (void)action_btnClick:(UIButton *)sender{
    switch (sender.tag - 1000) {
        case 0:
        {
            //增加
            
            //系统联系人添加界面
            self.contactViewController = [CNContactViewController viewControllerForNewContact:nil];
            self.contactViewController.delegate = self;
            
            self.navigationController = [[UINavigationController alloc] initWithRootViewController:self.contactViewController];
            self.navigationController.view.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
            [self addSubview:self.navigationController.view];
            
            
            
        }
            break;
            
        case 1:
        {
            //删除
            if (_personList.count == 0) {
                return;
            }
            [self deleteContact:_contactList[_selectIndex]];
        }
            break;
            
        default:
            break;
    }
}


//赋值
- (void)insetValueWithDictionary:(NSDictionary *)dic {
    
    _headerImageView.image = [UIImage imageWithData:dic[@"imageData"]];
    _personName.text = dic[@"personName"];
    
    NSArray *array = @[@"",dic[@"phoneNumber"],@"",dic[@"workAddress"]];
    
    NSInteger index = 0;
    
    for (UIView *view in [self subviews]) {
        
        if ([view isKindOfClass:[UILabel class]]) {
            
            if (view.tag >= 1000) {
                ((UILabel *)view).text = array[index];
                index++;
                
                if (index >= 4) {
                    return;
                }
            }
        }
        
    }
}


#pragma mark - CNContactViewControllerDelegate
- (void)contactViewController:(CNContactViewController *)viewController didCompleteWithContact:(CNContact *)contact{
    [self initDataSource];
    [self.navigationController.view removeFromSuperview];
    
}

- (BOOL)contactViewController:(CNContactViewController *)viewController shouldPerformDefaultActionForContactProperty:(CNContactProperty *)property{
    
    return YES;
}


#pragma mark - uitableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _personList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"listcell" forIndexPath:indexPath];
    cell.textLabel.text = _personList[indexPath.row][@"personName"];
    cell.textLabel.font = [UIFont systemFontOfSize:FONT_SIZE];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //选中的行赋值
    _selectIndex = indexPath.row;
    
    [self insetValueWithDictionary:_personList[indexPath.row]];
    
}

#pragma mark - getter
- (UITableView *)list{
    if (!_list) {
        _list = [[UITableView alloc] initWithFrame:CGRectMake(_cKwidth * 0.01, _cKheight * 0.18, _cKwidth * 0.35, _cKheight * 0.8)];
        _list.delegate = self;
        _list.dataSource= self;
        
        [_list registerClass:[UITableViewCell class] forCellReuseIdentifier:@"listcell"];
    }
    return _list;
}

- (CNContactStore *)contactStore{
    if (!_contactStore) {
        _contactStore = [[CNContactStore alloc] init];
    }
    return _contactStore;
}
@end
